home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 1.toast / Sample Code / Graphics 2D / CopyBits vs. CopyMask / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-28  |  19.1 KB  |  566 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        Sample.c
  3.  
  4.     Contains:    Sample is an example application that demonstrates how to
  5.                 initialize the commonly used toolbox managers, operate 
  6.                 successfully under MultiFinder, handle desk accessories, 
  7.                 and create, grow, and zoom windows.
  8.     
  9.                 It does not by any means demonstrate all the techniques 
  10.                 you need for a large application. In particular, Sample 
  11.                 does not cover exception handling, multiple windows/documents, 
  12.                 sophisticated memory management, printing, or undo. All of 
  13.                 these are vital parts of a normal full-sized application.
  14.     
  15.                 This application is an example of the form of a Macintosh 
  16.                 application; it is NOT a template. It is NOT intended to be 
  17.                 used as a foundation for the next world-class, best-selling, 
  18.                 600K application. A stick figure drawing of the human body may 
  19.                 be a good example of the form for a painting, but that does not 
  20.                 mean it should be used as the basis for the next Mona Lisa.
  21.     
  22.                 We recommend that you review this program or TESample before 
  23.                 beginning a new application.
  24.                 
  25.                 SetPort strategy:
  26.  
  27.                   Toolbox routines do not change the current port. In spite of this, in this
  28.                   program we use a strategy of calling SetPort whenever we want to draw or
  29.                    make calls which depend on the current port. This makes us less vulnerable
  30.                    to bugs in other software which might alter the current port (such as the
  31.                    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  32.                    Hopefully, this also makes the routines from this program more self-contained,
  33.                    since they don't depend on the current port setting.
  34.  
  35.     Written by:     
  36.  
  37.     Copyright:    Copyright © 1999 by Apple Computer, Inc., All Rights Reserved.
  38.  
  39.                 You may incorporate this Apple sample source code into your program(s) without
  40.                 restriction. This Apple sample source code has been provided "AS IS" and the
  41.                 responsibility for its operation is yours. You are not permitted to redistribute
  42.                 this Apple sample source code as "Apple sample source code" after having made
  43.                 changes. If you're going to re-distribute the source, we require that you make
  44.                 it clear in the source that the code was descended from Apple sample source
  45.                 code, but that you've made changes.
  46.  
  47.     Change History (most recent first):
  48.                 7/9/1999    Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
  49.                 
  50.  
  51. */
  52.  
  53. #pragma segment Main
  54.  
  55. #include <SegLoad.h>
  56. #include <ToolUtils.h>
  57. #include <DiskInit.h>
  58. #include <Processes.h>
  59. #include <Devices.h>
  60. #include <limits.h>
  61. #include "Test.h"
  62. #include "Sample.h"        /* bring in all the #defines for Sample */
  63.  
  64. /* The "g" prefix is used to emphasize that a variable is global. */
  65.  
  66. /* GMac is used to hold the result of a SysEnvirons call. This makes
  67.    it convenient for any routine to check the environment. */
  68. SysEnvRec    gMac;                /* set up by Initialize */
  69.  
  70. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  71.    trap is available. If it is false, we know that we must call GetNextEvent. */
  72. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  73.  
  74. /* GInBackground is maintained by our osEvent handling routines. Any part of
  75.    the program can check it to find out if it is currently in the background. */
  76. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  77.  
  78.  
  79. /* The following globals are the state of the window. If we supported more than
  80.    one window, they would be attatched to each document, rather than globals. */
  81.  
  82. /* GStopped tells whether the stop light is currently on stop or go. */
  83. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  84.  
  85. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  86. Rect        gStopRect;            /* set up by Initialize */
  87. Rect        gGoRect;            /* set up by Initialize */
  88.  
  89.  
  90. /* Define HiWrd and LoWrd macros for efficiency. */
  91. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  92. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  93.  
  94. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  95.    dependency on the ordering of fields within a Rect */
  96. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  97. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  98.  
  99.  
  100.  
  101.  
  102. void main()
  103. {
  104.     /* 1.01 - call to ForceEnvirons removed */
  105.     
  106.     /*    If you have stack requirements that differ from the default,
  107.         then you could use SetApplLimit to increase StackSpace at 
  108.         this point, before calling MaxApplZone. */
  109.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  110.  
  111.     Initialize();                    /* initialize the program */
  112.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  113.  
  114.     EventLoop();                    /* call the main event loop */
  115. }
  116.  
  117.  
  118. /*    Get events forever, and handle them by calling DoEvent.
  119.     Get the events by calling WaitNextEvent, if it's available, otherwise
  120.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  121.  
  122. void EventLoop()
  123. {
  124.     RgnHandle    cursorRgn;
  125.     Boolean        gotEvent;
  126.     EventRecord    event;
  127.     Point        mouse;
  128.  
  129.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  130.     do {
  131.         /* use WNE if it is available */
  132.         if ( gHasWaitNextEvent ) {
  133.             GetGlobalMouse(&mouse);
  134.             AdjustCursor(mouse, cursorRgn);
  135.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, nil);
  136.         }
  137.         else {
  138.             SystemTask();
  139.             gotEvent = GetNextEvent(everyEvent, &event);
  140.         }
  141.  
  142.         if ( gotEvent ) {
  143.             /* make sure we have the right cursor before handling the event */
  144.             AdjustCursor(event.where, cursorRgn);
  145.  
  146.             if (FrontWindow() && IsDialogEvent(&event)) {
  147.                 HandleDialogEvent(&event);
  148.             } else {
  149.                 HandleNormalEvent(&event);
  150.             }
  151.         }
  152.  
  153.         /*    If you are using modeless dialogs that have editText items,
  154.             you will want to call IsDialogEvent to give the caret a chance
  155.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  156.             for a non-NIL value before calling IsDialogEvent. */
  157.  
  158.     } while ( true );    /* loop forever; we quit via ExitToShell */
  159. } /*EventLoop*/
  160.  
  161.  
  162. /* Do the right thing for an event. Determine what kind of event it is, and call
  163.  the appropriate routines. */
  164.  
  165. void HandleNormalEvent(EventRecord *event)
  166. {
  167.     short        part, err;
  168.     WindowPtr    window;
  169.     Boolean        hit;
  170.     char        key;
  171.     Point        aPoint;
  172.  
  173.     switch ( event->what ) {
  174.         case mouseDown:
  175.             part = FindWindow(event->where, &window);
  176.             switch ( part ) {
  177.                 case inMenuBar:                /* process a mouse menu command (if any) */
  178.                     AdjustMenus();
  179.                     DoMenuCommand(MenuSelect(event->where));
  180.                     break;
  181.                 case inSysWindow:            /* let the system handle the mouseDown */
  182.                     SystemClick(event, window);
  183.                     break;
  184.                 case inContent:
  185.                     if ( window != FrontWindow() ) {
  186.                         SelectWindow(window);
  187.                         /*HandleNormalEvent(event);*/    /* use this line for "do first click" */
  188.                     } else
  189.                         DoContentClick(window);
  190.                     break;
  191.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  192.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  193.                     break;
  194.                 case inGrow:
  195.                     break;
  196.                 case inZoomIn:
  197.                 case inZoomOut:
  198.                     hit = TrackBox(window, event->where, part);
  199.                     if ( hit ) {
  200.                         SetPort(window);                /* the window must be the current port... */
  201.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  202.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  203.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  204.                     }
  205.                     break;
  206.             }
  207.             break;
  208.         case keyDown:
  209.         case autoKey:                        /* check for menukey equivalents */
  210.             key = event->message & charCodeMask;
  211.             if ( event->modifiers & cmdKey )            /* Command key down */
  212.                 if ( event->what == keyDown ) {
  213.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  214.                     DoMenuCommand(MenuKey(key));
  215.                 }
  216.             break;
  217.         case activateEvt:
  218.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  219.             break;
  220.         case updateEvt:
  221.             DoUpdate((WindowPtr) event->message);
  222.             break;
  223.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  224.             to a diskEvt, so that the user can format a floppy. */
  225.         case diskEvt:
  226.             if ( HiWord(event->message) != noErr ) {
  227.                 SetPt(&aPoint, kDILeft, kDITop);
  228.                 err = DIBadMount(aPoint, event->message);
  229.             }
  230.             break;
  231.         case kOSEvent:
  232.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  233.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  234.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  235.                     gInBackground = (event->message & kResumeMask) == 0;
  236.                     DoActivate(FrontWindow(), !gInBackground);
  237.                     break;
  238.             }
  239.             break;
  240.     }
  241. } /*HandleNormalEvent*/
  242.  
  243. void HandleDialogEvent(EventRecord *event)
  244. {
  245.     OSErr        err;
  246.     char        key;
  247.     Point        aPoint;
  248.     short         itemHit;
  249.     DialogPtr    dialog;
  250.  
  251.     switch ( event->what ) {
  252.         case keyDown:
  253.         case autoKey:                        /* check for menukey equivalents */
  254.             key = event->message & charCodeMask;
  255.             if ( event->modifiers & cmdKey )            /* Command key down */
  256.                 if ( event->what == keyDown ) {
  257.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  258.                     DoMenuCommand(MenuKey(key));
  259.                 }
  260.             break;
  261.         case diskEvt:
  262.             if ( HiWord(event->message) != noErr ) {
  263.                 SetPt(&aPoint, kDILeft, kDITop);
  264.                 err = DIBadMount(aPoint, event->message);
  265.             }
  266.             break;
  267.         default:
  268.             if (DialogSelect(event, &dialog, &itemHit)) {
  269.                 if (itemHit == kReadySetGoButton) {
  270.                     LetTheGameBegin(dialog);
  271.                 }
  272.             }
  273.     }
  274. }
  275.  
  276. /*    Change the cursor's shape, depending on its position. This also calculates the region
  277.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  278.     that region, an event would be generated, causing this routine to be called,
  279.     allowing us to change the region to the region the mouse is currently in. If
  280.     there is more to the event than just “the mouse moved”, we get called before the
  281.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  282.     this is called again before we     fall back into WNE. */
  283.  
  284. void AdjustCursor()
  285. {
  286.     WindowPtr    window;
  287.     //RgnHandle    arrowRgn;
  288.     //RgnHandle    plusRgn;
  289.     //Rect        globalPortRect;
  290.  
  291.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  292.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  293.     }
  294. } /*AdjustCursor*/
  295.  
  296.  
  297. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  298.     it will return either a pending event or a null event. In either case,
  299.     the where field of the event record will contain the current position
  300.     of the mouse in global coordinates and the modifiers field will reflect
  301.     the current state of the modifiers. Another way to get the global
  302.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  303.     being sure that thePort is set to a valid port. */
  304.  
  305. void GetGlobalMouse(Point *mouse)
  306. {
  307.     EventRecord    event;
  308.     
  309.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  310.     *mouse = event.where;                /* just the mouse position */
  311. } /*GetGlobalMouse*/
  312.  
  313.  
  314. /*    This is called when an update event is received for a window.
  315.     It calls DrawWindow to draw the contents of an application window.
  316.     As an effeciency measure that does not have to be followed, it
  317.     calls the drawing routine only if the visRgn is non-empty. This
  318.     will handle situations where calculations for drawing or drawing
  319.     itself is very time-consuming. */
  320.  
  321. void DoUpdate(WindowPtr window)
  322. {
  323.     if ( IsAppWindow(window) ) {
  324.         BeginUpdate(window);                /* this sets up the visRgn */
  325.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  326.             DrawWindow(window);
  327.         EndUpdate(window);
  328.     }
  329. } /*DoUpdate*/
  330.  
  331.  
  332. /*    This is called when a window is activated or deactivated.
  333.     In Sample, the Window Manager's handling of activate and
  334.     deactivate events is sufficient. Other applications may have
  335.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  336.  
  337. void DoActivate(WindowPtr window, Boolean becomingActive)
  338. {
  339.     if ( IsAppWindow(window) ) {
  340.         if ( becomingActive )
  341.             /* do whatever you need to at activation */ ;
  342.         else
  343.             /* do whatever you need to at deactivation */ ;
  344.     }
  345. } /*DoActivate*/
  346.  
  347.  
  348. /*    This is called when a mouse-down event occurs in the content of a window.
  349.     Other applications might want to call FindControl, TEClick, etc., to
  350.     further process the click. */
  351.  
  352. void DoContentClick()
  353. {
  354. } /*DoContentClick*/
  355.  
  356.  
  357. /* Draw the contents of the application window. We do some drawing in color, using
  358.    Classic QuickDraw's color capabilities. This will be black and white on old
  359.    machines, but color on color machines. At this point, the window’s visRgn
  360.    is set to allow drawing only where it needs to be done. */
  361.  
  362. void DrawWindow(WindowPtr window)
  363. {
  364.     SetPort(window);
  365. } /*DrawWindow*/
  366.  
  367.  
  368. /*    Enable and disable menus based on the current state.
  369.     The user can only select enabled menu items. We set up all the menu items
  370.     before calling MenuSelect or MenuKey, since these are the only times that
  371.     a menu item can be selected. Note that MenuSelect is also the only time
  372.     the user will see menu items. This approach to deciding what enable/
  373.     disable state a menu item has the advantage of concentrating all
  374.     the decision-making in one routine, as opposed to being spread throughout
  375.     the application. Other application designs may take a different approach
  376.     that is just as valid. */
  377.  
  378. void AdjustMenus()
  379. {
  380.     WindowPtr    window;
  381.     MenuHandle    menu;
  382.  
  383.     window = FrontWindow();
  384.  
  385.     menu = GetMenuHandle(mFile);
  386.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  387.         EnableItem(menu, iClose);
  388.     else
  389.         DisableItem(menu, iClose);    /* but not our traffic light window */
  390.  
  391.     menu = GetMenuHandle(mEdit);
  392.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  393.         EnableItem(menu, iUndo);
  394.         EnableItem(menu, iCut);
  395.         EnableItem(menu, iCopy);
  396.         EnableItem(menu, iClear);
  397.         EnableItem(menu, iPaste);
  398.     } else {                        /* …but we don’t use it */
  399.         DisableItem(menu, iUndo);
  400.         DisableItem(menu, iCut);
  401.         DisableItem(menu, iCopy);
  402.         DisableItem(menu, iClear);
  403.         DisableItem(menu, iPaste);
  404.     }
  405. } /*AdjustMenus*/
  406.  
  407.  
  408. /*    This is called when an item is chosen from the menu bar (after calling
  409.     MenuSelect or MenuKey). It performs the right operation for each command.
  410.     It is good to have both the result of MenuSelect and MenuKey go to
  411.     one routine like this to keep everything organized. */
  412.  
  413. void DoMenuCommand(long menuResult)
  414. {
  415.     short        menuID;                /* the resource ID of the selected menu */
  416.     short        menuItem;            /* the item number of the selected menu */
  417.     short        itemHit;
  418.     Str255        daName;
  419.     short        daRefNum;
  420.     Boolean        handledByDA;
  421.  
  422.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  423.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  424.     switch ( menuID ) {
  425.         case mApple:
  426.             switch ( menuItem ) {
  427.                 case iAbout:        /* bring up alert for About */
  428.                     itemHit = Alert(rAboutAlert, nil);
  429.                     break;
  430.                 default:            /* all non-About items in this menu are DAs */
  431.                     /* type Str255 is an array in MPW 3 */
  432.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  433.                     daRefNum = OpenDeskAcc(daName);
  434.                     break;
  435.             }
  436.             break;
  437.         case mFile:
  438.             switch ( menuItem ) {
  439.                 case iClose:
  440.                     DoCloseWindow(FrontWindow());
  441.                     break;
  442.                 case iQuit:
  443.                     Terminate();
  444.                     break;
  445.             }
  446.             break;
  447.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  448.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  449.             break;
  450.     }
  451.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  452. } /*DoMenuCommand*/
  453.  
  454.  
  455.  
  456. /* Close a window. This handles desk accessory and application windows. */
  457.  
  458. /*    1.01 - At this point, if there was a document associated with a
  459.     window, you could do any document saving processing if it is 'dirty'.
  460.     DoCloseWindow would return true if the window actually closed, i.e.,
  461.     the user didn’t cancel from a save dialog. This result is handy when
  462.     the user quits an application, but then cancels the save of a document
  463.     associated with a window. */
  464.  
  465. Boolean DoCloseWindow(WindowPtr window)
  466. {
  467.     if ( IsDAWindow(window) )
  468.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  469.     else if ( IsAppWindow(window) )
  470.         CloseWindow(window);
  471.     return true;
  472. } /*DoCloseWindow*/
  473.  
  474.  
  475. /**************************************************************************************
  476. *** 1.01 DoCloseBehind(window) was removed ***
  477.  
  478.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  479.     and not having to worry about updating the windows, but it suffered
  480.     from a fatal flaw. If a desk accessory owned two windows, it would
  481.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  482.     got around to calling DoCloseWindow for that other window that was already
  483.     closed, things would go very poorly. Another option would be to have a
  484.     procedure, GetRearWindow, that would go through the window list and return
  485.     the last window. Instead, we decided to present the standard approach
  486.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  487.     has a potential benefit in that the window whose document needs to be saved
  488.     may be visible since it is the front window, therefore decreasing the
  489.     chance of user confusion. For aesthetic reasons, the windows in the
  490.     application should be checked for updates periodically and have the
  491.     updates serviced.
  492. **************************************************************************************/
  493.  
  494.  
  495. /* Clean up the application and exit. We close all of the windows so that
  496.  they can update their documents, if any. */
  497.  
  498. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  499.     shell, but will return instead. */
  500.  
  501. void Terminate()
  502. {
  503.     WindowPtr    aWindow;
  504.     Boolean        closed;
  505.     
  506.     closed = true;
  507.     do {
  508.         aWindow = FrontWindow();                /* get the current front window */
  509.         if (aWindow != nil)
  510.             closed = DoCloseWindow(aWindow);    /* close this window */    
  511.     }
  512.     while (closed && (aWindow != nil));
  513.  
  514.     if (closed)
  515.         ExitToShell();                            /* exit if no cancellation */
  516. } /*Terminate*/
  517.  
  518. /*    Check to see if a window belongs to the application. If the window pointer
  519.     passed was NIL, then it could not be an application window. WindowKinds
  520.     that are negative belong to the system and windowKinds less than userKind
  521.     are reserved by Apple except for windowKinds equal to dialogKind, which
  522.     mean it is a dialog.
  523.     1.02 - In order to reduce the chance of accidentally treating some window
  524.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  525.     is userKind. If you add different kinds of windows to Sample you'll need
  526.     to change how this all works. */
  527.  
  528. Boolean IsAppWindow(WindowPtr window)
  529. {
  530.     short        windowKind;
  531.  
  532.     if ( window == nil )
  533.         return false;
  534.     else {    /* application windows have windowKinds = userKind (8) */
  535.         windowKind = ((WindowPeek) window)->windowKind;
  536.         return ( windowKind == userKind || windowKind == dialogKind);
  537.     }
  538. } /*IsAppWindow*/
  539.  
  540.  
  541. /* Check to see if a window belongs to a desk accessory. */
  542.  
  543. Boolean IsDAWindow(WindowPtr window)
  544. {
  545.     if ( window == nil )
  546.         return false;
  547.     else    /* DA windows have negative windowKinds */
  548.         return ( ((WindowPeek) window)->windowKind < 0 );
  549. } /*IsDAWindow*/
  550.  
  551.  
  552. /*    Display an alert that tells the user an error occurred, then exit the program.
  553.     This routine is used as an ultimate bail-out for serious errors that prohibit
  554.     the continuation of the application. Errors that do not require the termination
  555.     of the application should be handled in a different manner. Error checking and
  556.     reporting has a place even in the simplest application. The error number is used
  557.     to index an 'STR#' resource so that a relevant message can be displayed. */
  558.  
  559. void AlertUser()
  560. {
  561.     short        itemHit;
  562.  
  563.     SetCursor(&qd.arrow);
  564.     itemHit = Alert(rUserAlert, nil);
  565.     ExitToShell();
  566. } /* AlertUser */